/*
 FilmAffinity++

 Version 2.0.5
 5 de marzo de 2009
 Basado en FilmAffinityPlus por Javier Arias http://javierarias.wordpress.com/scripts/filmaffinityplus/
 Released under the GPL license
 http://www.gnu.org/copyleft/gpl.html

 Website: http://www.buxo.org/filmaffinity/

 @todo:
 -detectar Opera
 -Historico de cambios en almas gemelas
 -Leyenda en almas gemelas
 -Opción de ocultar menus originales
 -Listas: subir y bajar peliculas con icono
 -Aplicar limites a otras listas

 Changelog
 * 2.0.5, 5 de Marzo de 2009
 Corregida pantalla selección de listas para nº grande de listas

 * 2.0.4, 4 de marzo de 2009 (publica)
 Añadidos almas gemelas caidas y fecha de ultimos cambios. 
 Ocultar enlaces por tipo
 Modificado el codigo para guardar las preferencias
 Posibilidad de modificar el nº de peliculas que aparecen en las listas de recomendaciones y TOP

 * 2.0.3, 3 de marzo de 2009 (interna)
 Añadido el control de cambios en almas gemelas
 Añadidas opciones para activar/desactivar los nuevos cambios

 * 2.0.2, 2 de marzo de 2009 (interna)
 Añadido el sistema rapido para añadir a listas

 * 2.0.1, 1 de marzo de 2009 (interna)
 Integrados los menus en la barra izquierda
 Integrados enlaces en la ficha de la pelicula

 * 1.2.0 -> FilmAffinityPlus por Javier Arias

 * 1.2.0, 26 de agosto de 2008
 Añadida la opción para abrir los enlaces en nueva ventana (muy solicitado).
 Ahora se utiliza la versión en castellano de IMDb.
 Cambio de imagen del panel de configuración.
 Añadido el sitio de información general Rotten Tomatoes (petición de Jerry Lucas).
 Añadidos los siguientes sitios de descargas: aRGENTeaM, titles.box.sk y fileheaven (petición de aixa-impaciente).
 Añadido el sitio de descarga directa Taringa!.
 Arreglada la búsqueda en CINeol.
 Se indica cuáles de los sitios web a los que enlaza el script requieren registro.
 En el log se muestra la versión del script, útil para buscar y corregir errores.
 Se puede acceder fácilmente a la información de depurado pulsando en el título de la barra de FilmAffinityPlus.

 * 1.1.0, 27 de junio de 2008
 Añadida una barra en la parte superior izquierda de la pantalla, con botones para acceder al panel de configuración, a la web oficial y para añadir FilmAffinity a los motores de búsqueda de Firefox.
 Añadida una opción para cambiar el estilo de las estrellas de puntuación. Se incluyen dos esquemas: uno de estrellas rojas y otro de estrellas amarillas, además de la posibilidad de dejar las estrellas que vienen por defecto.
 Los enlaces a otros sitios web se muestran también en la página de resultados de una búsqueda.
 Tras realizar una búsqueda se guarda la opción de búsqueda realizada (ej: una búsqueda por "Reparto" deja seleccionada la opción "Reparto", actualmente tras cualquier tipo de búsqueda la opción seleccionada es siempre "Todas"). Además, tras la búsqueda el cuadro de búsqueda se queda con el foco del teclado.
 Arreglada la búsqueda en otros sitios web cuando los títulos contenían caracteres "raros", como tildes o acentos circunflejos (gracias aka_IDIOT).
 Se cambia el enlace a la versión inglesa de FilmAffinity para que apunte a la misma página en inglés, actualmente apunta siempre a la página principal (ej: desde la ficha de una película se va a la versión inglesa de la ficha).
 Cambiado el antiguo webchat por su nueva versión en flash.
 Recuperado el sitio de subtítulos solosubtitulos.com pues parece que vuelve a funcionar.
 Añadido un enlace externo a "el grupo de last.fm que surgió del foro que surgió de FilmAffinity" (sugerencia de VicenteJavier).
 Se muestra la bandera de cada país en la sección "Mis datos", también en la búsqueda avanzada y en los TOP FilmAffinity.
 En la sección "Mis datos" se añade a las estadísticas el número de países diferentes con películas vistas.
 Las búsquedas para AllZine (gracias VicenteJavier) y para Cinépatas (gracias pohc) se realizan con el título traducido debido a que la tasa de aciertos es mucho mayor que con el título original.
 Añadido el sitio de descargas Vagos.es (petición de Soisa y de un usuario anónimo).
 Correcciones menores.

 * 1.0.1, 14 de mayo de 2008
 Cambiado ligeramente el CSS del panel de configuración.
 Correcciones menores.

 * 1.0.0, 12 de mayo de 2008
 Primera versión pública.
 Eliminada la búsqueda de subtítulos en solosubtitulos.com pues la página ha desaparecido.

 * 0.9.9, 25 de abril de 2008
 Arreglada la búsqueda en La Butaca.

 * 0.9.8, 23 de abril de 2008
 Para los enlaces a otros sitios web se utiliza el título original, no el traducido.
 Arreglada de nuevo la búsqueda en Google (gracias jota724).
 La notificación de cambios en el número de votos de Mis amigos también funciona para usuarios validadores de críticas, tal vez funcione para el resto de administradores (gracias jota724).

 * 0.9.7, 21 de abril de 2008
 Ahora el script funciona también para usuarios validadores de críticas, tal vez funcione para el resto de administradores (gracias jota724).
 Si no hay seleccionado ningún enlace de alguna categoría no se muestra ésta en la ficha de la película (gracias Zopilote).
 Arreglada la búsqueda en Alpacine (gracias Manhoman).
 Añadido DivX Clásico (petición de Grandine).

 * 0.9.6, 20 de abril de 2008
 'Secciones externas' aparecía incorrectamente en las páginas de estadísticas (gracias aka_IDIOT).
 Arreglada la búsqueda en Google (gracias aka_IDIOT).
 Arreglado pequeño fallo al cargar las preferencias cuando el tipo de dato era 'undefined'.
 Añadido Cine-Clásico (petición de Grandine).
 Añadido Cinépatas (petición de Zopilote).
 Añadido AllZine (petición de Grandine).

 * 0.9.5, 18 de abril de 2008
 Primera versión beta pública.

 */
// ==UserScript==
// @name           FilmAffinity++
// @namespace      http://www.filmaffinity.com/
// @description    Mejoras en FilmAffinity
// @include        http://www.filmaffinity.com/es/*
// @version 2.0.5
// ==/UserScript==

window.addEventListener("load", doFAPP(),false);

function doFAPP() {
    var d = document;
    var appName = "FilmAffinity++";
    var appVersion = '2.0.5';
    var homepage = 'http://www.buxo.org/filmaffinity/';
    var url = d.location.href;
    var isAdmin = d.body.innerHTML.search(/\/es\/adm\/reviews_val\.php/ig) > -1;
    var methodEncode = function(txt) {
        return encodeURIComponent(txt);
    };
    var methodEscape = function(txt) {
        return escape(txt.replace(/\s/g, '+'));
    };
    var _TFILM = 1;
    var _TGEN = 2;
    var _TDOWN = 3;
    var _TSUB = 4;
    var ANCHOR_AFTER = 1;
    var ANCHOR_BEFORE = 2;
    var debuglog = '<u><strong>INFORMACIÓN DE DEPURADO</strong></u>';

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };

    //http://www.iconarchive.com/category/funny/kidcons-icons-by-iconfactory.html
    var ratingStyles = {
        red: { name: 'Estrellas rojas', code: 'red', iconOn: '',
            iconOff: '',
            iconHalf: '' },
        yellow: { name: 'Estrellas amarillas', code: 'yellow', iconOn: '%3D',
            iconOff: '',
            iconHalf: '' }
    };

    var waitimg = '%2F%2F%2Fzhfh3qUr0hskWSCocjS3ai5yiZRfBpHdUJnjeDm7Pr6%2BwAAAAAAAAAAACH%2BGkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ%2FV%2FnmOM82XiHRLYKhKP1oZmADdEAAAh%2BQQACgABACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY%2FCZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB%2BA4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6%2BHo7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq%2BB6QDtuetcaBPnW6%2BO7wDHpIiK9SaVK5GgV543tzjgGcghAgAh%2BQQACgACACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxM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2FIacYP%2FjYh%2BHUq5PkGe42Id3Bu5uQbJElbayI3BE%2BeoHQXITW6lXHfgZ4P0Jez%2F5duOLWX5l7bUg2SdqbpIUH6B%2BZIx1%2FFE68TDT7HIWpJyk8dApypkEXgXoAairWHu91Wu5VTmBlZJNnKB56mOzeL8STZ1FxiKh%2BGlbmca%2BNylWcbL2rSF9FROFaOHbhzVCdCKpMEM2epzBSg36XEALcvU6hfpJoZ5W4cpi8dYdoZAKsF2wfj996qXbT23ehnz6hcj1khRqhOoGTbUKxhFrL0FgkX%2FiEfO0Psns%2F4mQD5CkgDoY77m6%2BHQ03X3drpWRKeP0GUb9Ltr6ImjfoN1fZV06xAP6xeUPS92HQjK5Gw4fGvLFE3LhF1FlFyQZ52sFo8GwN1N2TsC3pS9sDE8Hz2dqvtxFzsblk52CDYN%2F9AahcYhczCcxJ%2BikMguF58gzDTeCSBObA9wFsgO9Alw0l7AZocJltjJHogH%2BwuQy6tsffAr8jqSVp2faKYEnSugTB%2F0%2BY%2BV3Ss3tpGxY6jXjP9s%2FAx5jywVqDDP03ACQcUqlf5GWbAAAAAElFTkSuQmCC';

    var ratings = {
        1: "Muy mala",
        2: "Mala",
        3: "Floja",
        4: "Regular",
        5: "Pasable",
        6: "Interesante",
        7: "Buena",
        8: "Notable",
        9: "Muy buena",
        10: "Excelente"
    };

    var menus = {
        0: {name:'SECCIONES EXTERNAS',anchor:'SECCIONES',position:ANCHOR_AFTER,cond:'SHOWSEMENU',
            options: {0:{title: 'El Foro que surgió de FilmAffinity',
                href:'http://filmaffinity.mforos.com',
                target:'_blank'},
                1:{title: 'Chat NO OFICIAL en iRC-Hispano',
                    href:'http://www.irc-hispano.es/webchat/flash.php?canal=filmaffinity',
                    target:'_blank'},
                2:{title: 'El grupo de last.fm que surgió del foro que surgió de FilmAffinity',
                    href:'http://www.lastfm.es/group/El+grupo+que+surgi%C3%B3+del+foro+que+surgi%C3%B3+de+Filmaffinity',
                    target:'_blank'}
            }
        },
        1: {name:'FilmAffinity++',anchor:'USUARIOS',position:ANCHOR_BEFORE,cond:'SHOWSCRIPTMENU',
            options: {0: {title:'Panel de Configuración',href:'#',target:'',onclick:showPreferences},
                1: {title:'Web Oficial FA++',href:'#',target:'',onclick:goToHomepage},
                2: {title:'Añadir motor busqueda',href:'#',target:'',onclick:installSearchEngine},
                3: {title:'Información de depurado',href:'#',target:'',onclick:showLog}
            }
        }};

    var preferencesOptions = {
        0:{name:'SHOWQUICKLIST',text:'Mostrar icono para añadir rapidamente a listas.',def:true},
        1:{name:'SHOWSMCHANGES',text:'Mostrar cambios en las almas gemelas.',def:true},
        2:{name:'SHOWSMFALLEN',text:'Mostrar las almas gemelas caidas de la lista.',def:true},
        3:{name:'KEEPSMCHANGES',text:'Mantener los cambios en las almas gemelas mientras no se produzcan nuevos cambios.',def:true},
        4:{name:'SHOWSEMENU',text:'Mostrar el menú Secciones Externas en la barra de la izquierda.',def:true},
        5:{name:'SHOWSCRIPTMENU',text:'Mostrar el menú FilmAffinity++ en la barra de la izquierda.',def:true},
        6:{name:'LINKSINPROFILE',text:'Integrar enlaces en la ficha de la pelicula.',def:true},
        7:{name:'CHANGELIMIT',text:'Cambiar el nº de peliculas a mostrar en Recomendaciones y TOP',def:false}
    };

    var linkSites = {
        imdb : { name: 'IMDb',
            icon: 'http://imdb.com/favicon.ico',
            search: 'http://spanish.imdb.com/find?q=%searchvo;tt=on;nm=on;mx=20',
            method: methodEncode,
            type: _TFILM
        },
        cineol : { name: 'CINeol',
            icon: 'http://www.cineol.net/favicon.ico',
            search: 'http://www.cineol.net/multisearch.php?fan=1&where=movies&search=%searchvo',
            method: methodEscape,
            type: _TFILM
        },
        cinepatas : { name: 'Cinépatas',
            icon: 'http://www.cinepatas.com/favicon.ico',
            search: 'http://www.cinepatas.com/forum/searcher.php?search_keywords=%searchtr&easy_search=titles',
            method: methodEscape,
            type: _TFILM
        },
        rotten : { name: 'Rotten Tomatoes',
            icon: 'http://www.rottentomatoes.com/favicon.ico',
            search: 'http://www.rottentomatoes.com/search/full_search.php?search=%searchvo',
            method: methodEscape,
            type: _TFILM
        },
        alpacine : { name: 'Alpacine',
            icon: 'http://www.alpacine.com/favicon.ico',
            search: 'http://www.alpacine.com/buscar/?buscar=%searchvo',
            method: methodEscape,
            type: _TFILM
        },
        labutaca : { name: 'La Butaca',
            icon: 'http://www.labutaca.net/favicon.ico',
            search: 'http://www.google.com/custom?q=%searchvo&sa=Buscar+en&sitesearch=www.labutaca.net&q=&domains=www.labutaca.net',
            method: methodEncode,
            type: _TFILM
        },
        /*	dvdreviews : { name: 'DVD-reviews',
         icon: 'http://www.dvd-reviews.net/favicon.ico',
         search: 'http://www.google.com/custom?q=%searchvo&sitesearch=dvd-reviews.net',
         type: _TFILM
         },*/
        yahoo : { name: 'Yahoo! Movies',
            icon: 'http://movies.yahoo.com/favicon.ico',
            search: 'http://movies.yahoo.com/mv/search?p=%searchvo&x=0&y=0&fr=ush-movies&toggle=1&cop=&ei=UTF-8',
            method: methodEncode,
            type: _TFILM
        },
        wikipedia : { name: 'Wikipedia',
            icon: 'http://en.wikipedia.org/favicon.ico',
            search: 'http://en.wikipedia.org/wiki/Special:Search?search=%searchvo&go=Go',
            method: methodEncode,
            type: _TGEN
        },
        wikipediaES : { name: 'Wikipedia ES',
            icon: '',
            search: 'http://es.wikipedia.org/w/index.php?title=Especial:Search&search=%searchvo&go=Go',
            method: methodEncode,
            type: _TGEN
        },
        google : { name: 'Google',
            icon: 'http://www.google.es/favicon.ico',
            search: 'http://www.google.es/search?q=%searchvo',
            method: methodEncode,
            type: _TGEN
        },
        mininova : { name: 'Mininova',
            icon: 'http://static.mininova.org/images/favicon.ico',
            search: 'http://www.mininova.org/search/%searchvo/4',
            method: methodEncode,
            type: _TDOWN
        },
        isohunt : { name: 'isoHunt',
            icon: 'http://isohunt.com/favicon.ico',
            search: 'http://isohunt.com/torrents/%searchvo?ihs1=2&iho1=d&iht=1',
            method: methodEncode,
            type: _TDOWN
        },
        piratebay : { name: 'The Pirate Bay',
            icon: 'http://thepiratebay.org/favicon.ico',
            search: 'http://thepiratebay.org/search/%searchvo/0/99/200',
            method: methodEncode,
            type: _TDOWN
        },
        youtorrent : { name: 'YouTorrent',
            icon: 'http://www.youtorrent.com/favicon.ico',
            search: 'http://www.youtorrent.com/tag/%searchvo',
            method: methodEscape,
            type: _TDOWN
        },
        cineclasico : { name: 'Cine-Clásico',
            icon: 'http://www.cine-clasico.com/favicon.ico',
            search: 'http://www.cine-clasico.com/foros/search.php?keywords=%searchvo&terms=all&author=&sc=1&sf=firstpost&sr=posts&sk=t&sd=d&st=0&ch=300&t=0&submit=Buscar',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        divxclasico : { name: 'DivX Clásico',
            icon: 'http://www.divxclasico.com/favicon.ico',
            search: 'http://www.divxclasico.com/foro/search.php?search_keywords=%searchvo&highlight=%searchvo',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        allzine : { name: 'AllZine',
            icon: '%3D',
            search: 'http://www.allzine.org/Foro/index.php?action=search2&search=%searchtr&subject_only=1',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        vagos : { name: 'Vagos.es',
            icon: 'http://www.vagos.es/favicon.ico',
            search: 'http://buscador.wamba.com/buscar/index.php?cx=004825717204032381724%3Ajfqcclqsbpi&cof=FORID%3A11&q=%searchtr',
            method: methodEncode,
            type: _TDOWN
        },
        clansa : { name: 'Clan-Sudamérica',
            icon: 'http://www.clan-sudamerica.com.ar/favicon.ico',
            search: 'http://www.clan-sudamerica.com.ar/invision/index.php?act=Search&CODE=01&keywords=%searchtr&namesearch=&forums%5B%5D=all&searchsubs=1&prune=0&prune_type=newer&sort_key=last_post&sort_order=desc&search_in=titles&result_type=topics',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        argenteam : { name: 'aRGENTeaM',
            icon: 'http://www.argenteam.net/favicon.ico',
            search: 'http://foro.argenteam.net/search.php?keywords=%searchvo&terms=all&author=&fid%5B%5D=68&fid%5B%5D=69&fid%5B%5D=70&sc=1&sf=firstpost&sr=posts&sk=t&sd=d&st=0&ch=500&t=0&submit=Buscar',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        fileheaven : { name: 'fileheaven',
            icon: 'http://www.fileheaven.org/favicon.ico',
            search: 'http://www.fileheaven.org/forum/search.php?mode=results&search_keywords=%searchvo&search_terms=all&search_author=&search_forum=-1&search_time=0&search_fields=subjonly&search_cat=-1&sort_by=0&sort_dir=DESC&show_results=topics&return_chars=200',
            method: methodEncode,
            regreq: true,
            type: _TDOWN
        },
        taringa : { name: 'Taringa!',
            icon: 'http://www.taringa.net/favicon.ico',
            search: 'http://www.taringa.net/buscador/?q=%searchvo&categoria=13&sort_by=0&autor=',
            method: methodEncode,
            type: _TDOWN
        },
        opensubtitles : { name: 'OpenSubtitles',
            icon: 'http://static.opensubtitles.org/favicon.ico',
            search: 'http://www.opensubtitles.com/es/search2/sublanguageid-spa/moviename-%searchvo',
            method: methodEncode,
            type: _TSUB
        },
        solosubtitulos : { name: 'solosubtitulos',
            icon: 'http://www.solosubtitulos.com/imagenes_web/favicon.ico',
            search: 'http://www.solosubtitulos.com/?q=%searchvo',
            method: methodEscape,
            type: _TSUB
        },
        subdivx : { name: 'SubDivX',
            icon: 'http://www.subdivx.com/favicon.ico',
            search: 'http://www.subdivx.com/index.php?buscar=%searchvo&accion=5&subtitulos=1&realiza_b=1',
            method: methodEscape,
            type: _TSUB
        },
        titles : { name: 'titles.box.sk',
            icon: '%3D',
            search: 'http://titles.box.sk/index.php?z3=%searchvo&rad1=an&aka=1&alt=1&jaz=9&z=datum+desc&days=0&pid=subt2&p=as&cas=1215777572&bt1=ADVANCED+SEARCH',
            method: methodEscape,
            type: _TSUB
        }
    };

    /*
     getElementsByClassName
     Written by Jonathan Snook, http://www.snook.ca/jonathan
     Add-ons by Robert Nyman, http://www.robertnyman.com
     */

    function getElementsByClassName(oElm, strTagName, strClassName) {
        var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        strClassName = strClassName.replace(/\-/g, "\\-");
        var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
        var oElement;
        for (var i = 0; i < arrElements.length; i++) {
            oElement = arrElements[i];
            if (oRegExp.test(oElement.className)) {
                arrReturnElements.push(oElement);
            }
        }
        return (arrReturnElements);
    }
    
    function formatDate (fDate) {
      if (typeof fDate != 'undefined') {
  		  var yyyy = fDate.getFullYear();
  		  var m = fDate.getMonth()+1;
  		  var d = fDate.getDate();
		    var h = fDate.getHours();
		    var n = fDate.getMinutes();
		    var nn = n < 10 ? "0" + n : n;
  		  var s = fDate.getSeconds();
	   	  var ss = s < 10 ? "0" + s : s;

        return d+"/"+m+"/"+yyyy+" a las "+h+":"+nn+":"+ss;
      } else { return ""};
    }


    function post(url, data, cb) {
        GM_xmlhttpRequest({
            method: "POST",
            url: url,
            headers:{'Content-type':'application/x-www-form-urlencoded'},
            data:encodeURI(data),
            onload: function(xhr) {
                cb(xhr.responseText);
            }
        });
    }

    function log(msg) {
        debuglog += '<br/>' + msg;
        GM_log(msg);
    }

    function setPreference(name, value) {
        log('Guardo preferencia: ' + name + '=' + value);
        GM_setValue('cfg.' + name, value);
    }

    function getPreference(name, def) {
        def = (typeof def == "undefined") ? false : def;
        var r = GM_getValue('cfg.' + name);
        log('Saco preferencia: ' + name + '=' + r);
        return (typeof r == "undefined") ? def : r;
    }

    function getValues(start) {
        var result = [];
        var values = GM_listValues();
        for (ix in values) {
            var name = values[ix];
            if (name.indexOf(start) == 0) {
                result.push(name.substr(start.length));
            }
        }
        return result;
    }

    function deleteValues(start) {
        log("DeleteValues: ");
        var values = GM_listValues();
        for (var ix in values) {
            var name = values[ix];
            if (name.indexOf(start) == 0) {
                log("valor: " + values[ix]);
                GM_deleteValue(name);
            }
        }
    }


    function showLog() {
        GM_addStyle('#backgroundLayer { width: 100%; height: 100%; background-color: black; position: fixed; left: 0; right: 0; top: 0; bottom: 0; opacity: .7; }');
        GM_addStyle('#board { color: black; background-color: #def; text-align: left; border: 4px solid gray; width: 50%; height: 70%; opacity: 1; margin: auto; position: fixed; left: 0; right: 0; top: 0; bottom: 0; overflow: auto; }');
        var background = d.createElement('DIV');
        background.id = 'backgroundLayer';
        var board = d.createElement('div');
        board.id = 'board';
        board.innerHTML = '<code>' + debuglog + '</code>';
        d.body.appendChild(background);
        d.body.appendChild(board);
        d.getElementById("backgroundLayer").addEventListener("click", hideLog, true);
    }

    function hideLog() {
        d.body.removeChild(d.getElementById('board'));
        d.body.removeChild(d.getElementById('backgroundLayer'));
    }

    function goToHomepage() {
        location.href = homepage;
    }

    function isFlagImg(img) {
        return img.src.search(/\/countries\//ig) > -1;
    }

    function isRatingImg(img) {
        return img.src.search('http://www.filmaffinity.com/imgs/myratings/') > -1 || img.src.search('http://www.filmaffinity.com/imgs/ratings/') > -1;
    }

    // Funciones para localizarnos en filmAffinity
    // TODO: sustituir todas las funciones por un array y una función

    function inMyFriends() {
        return url.search(/myfriends\.php/ig) > -1;
    }

    function inStats() {
        return url.search(/userrep\.php\?user_id\=/ig) > -1;
    }

    function inFilm() {
        return url.search(/\/film/ig) > -1;
    }

    function inSearch() {
        return url.search(/\/search\.php/ig) > -1;
    }

    function inMyData() {
        return url.search(/\/mydata\.php/ig) > -1;
    }

    function inTopGen() {
        return url.search(/\/topgen\.php/ig) > -1;
    }

    function inAdvSearch() {
        return url.search(/\/advsearch\.php/ig) > -1;
    }

    function inSoulMates() {
        return url.search(/\/soulmates\.php/ig) > -1;
    }

    function inLists() {
        return url.search(/\/mylists\.php/ig) > -1;
    }

    function inTour() {
        return url.search(/\/tour\.php/ig) > -1;
    }

    function inSoulMatesRec() {
        return url.search(/\/smsrec\.php/ig) > -1;
    }

    function inUserRec() {
        return url.search(/\/userrec\.php/ig) > -1;
    }

    function inMyVotes() {
        return url.search(/\/myvotes\.php/ig) > -1;
    }

    function inAutotour() {
        return url.search(/\/autotour\.php/ig) > -1;
    }

    function getRatingFromImg(img) {
        if (img.src.search('myratings') > -1)
            return img.src.substring(new String('http://www.filmaffinity.com/imgs/myratings/').length, img.src.indexOf('.gif'));
        else
            return img.src.substring(new String('http://www.filmaffinity.com/imgs/ratings/').length, img.src.indexOf('.gif'));
    }

    function getCountryCode(country) {
        var countriesCodes = { "Afganistán": "AF", "Alemania": "DE", "Angola": "AO", "Argelia": "DZ", "Argentina": "AR", "Armenia": "AM", "Australia": "AU", "Austria": "AT", "Bélgica": "BE", "Bolivia": "BO", "Bosnia - Herzegovina": "BA", "Brasil": "BR", "Bulgaria": "BG", "Burkina Faso": "BF", "Bután": "BT", "Camboya": "KH", "Canadá": "CA", "Chad": "TD", "Checoslovaquia": "ZX", "Chile": "CL", "China": "CN", "Colombia": "CO", "Corea del Norte": "KP", "Corea del Sur": "KR", "Costa de Marfil": "CI", "Costa Rica": "CR", "Croacia": "HR", "Cuba": "CU", "Dinamarca": "DK", "Ecuador": "EC", "Egipto": "EG", "Eslovenia": "SI", "España": "ES", "Estados Unidos": "US", "Estonia": "EE", "Filipinas": "PH", "Finlandia": "FI", "Francia": "FR", "Georgia": "GE", "Grecia": "GR", "Guatemala": "GT", "Holanda": "NL", "Hong Kong": "HK", "Hungría": "HU", "India": "IN", "Indonesia": "ID", "Irak": "IQ", "Irán": "IR", "Irlanda": "IE", "Islandia": "IS", "Israel": "IL", "Italia": "IT", "Japón": "JP", "Kazajstán": "KZ", "Líbano": "LB", "Luxemburgo": "LU", "Macedonia": "MK", "Malasia": "MY", "Mali": "ML", "Marruecos": "MA", "México": "MX", "Mongolia": "MN", "Nepal": "NP", "Nicaragua": "NI", "Nigeria": "NG", "Noruega": "NO", "Nueva Zelanda": "NZ", "Panamá": "PA", "Paquistán": "PK", "Paraguay": "PY", "Perú": "PE", "Polonia": "PL", "Portugal": "PT", "Puerto Rico": "PR", "Reino Unido": "GB", "Rep. Dominicana": "DO", "República Checa": "CZ", "Rumanía": "RO", "Rusia": "RU", "Senegal": "SN", "Serbia": "RS", "Singapur": "SG", "Suecia": "SE", "Suiza": "CH", "Suráfrica": "ZA", "Tailandia": "TH", "Taiwán": "TW", "Territorios Palestinos": "PS", "Túnez": "TN", "Turquía": "TR", "URSS": "ZY", "Uruguay": "UY", "Venezuela": "VE", "Vietnam": "VN", "Yemen": "YE", "Yugoslavia": "YU" };
        return countriesCodes[country];
    }


    // ************************ PREFERENCIAS *********************************************

    function showPreferences() {
        log("Mostrar preferencias");

        GM_addStyle('#backgroundLayer { width: 100%; height: 100%; background-color: black; position: fixed; left: 0; right: 0; top: 0; bottom: 0; opacity: .7; }');
        GM_addStyle('#fap_prefs { color: black; background-color: #def; text-align: center; border: 4px solid gray; width: 70%; height: 90%; opacity: 1; margin: auto; position: fixed; left: 0; right: 0; top: 0; bottom: 0; overflow: auto; }');
        GM_addStyle('#fap_prefs>#closeButton { width: 22px; height: 22px; margin: 0; padding: 0; position: absolute; right: 0; top: 0; background-image: url(' + closeimg + '); opacity: .5; }');
        GM_addStyle('#fap_prefs>#closeButton:hover { opacity: 1; }');
        GM_addStyle('#fap_prefs>h1 { font-size: x-large; }');
        GM_addStyle('#fap_prefs>h2 { font-size: large; font-style: italic; }');
        GM_addStyle('#fap_prefs>table { border: 1; margin-left: auto; margin-right: auto; }');
        GM_addStyle('#fap_prefs>table>caption { border: 1; margin-left: auto; margin-right: auto; }');
        GM_addStyle('#fap_prefs>button { margin: 2em; }');
        GM_addStyle('#fap_prefs img { width: 16px; height: 16px; }');
        GM_addStyle('#fap_prefs th { background-color: black; color: white; font-style: italic; }');
        GM_addStyle('#fap_prefs>table { border: 1px solid black; }');
        GM_addStyle('#fap_prefs td.sites { border: 1px solid black; }');
        GM_addStyle('#fap_prefs label:hover { text-decoration: underline; }');
        GM_addStyle('#fap_prefs fieldset { width: 300px; margin-left: auto; margin-right: auto; }');
        GM_addStyle('#fap_prefs legend { font-weight: bold; }');
        GM_addStyle('#fap_prefs .regreq { font-weight: bold; color: red }');

        var background = d.createElement('DIV');
        background.id = 'backgroundLayer';
        d.body.appendChild(background);

        var prefs = d.createElement('DIV');
        prefs.id = 'fap_prefs';

        var tmp = '<div id="closeButton" title="Cierra el panel de configuración"></div><h1>' + appName + ' versión ' + appVersion + '</h1>';
        tmp += '<h2>Panel de configuración</h2>';
        //tmp += '<object data="http://petra.euitio.uniovi.es/~i1656488/star.svg" type="image/svg+xml" width="400" height="400"><embed src="http://petra.euitio.uniovi.es/~i1656488/star.svg" type="image/svg+xml" width="400" height="400" /></object>'
        tmp += '<table><caption>Mostrar enlaces a los siguientes sitios web:</caption>';
        tmp += '<thead><tr>';
        check = getPreference("verCine", true) ? 'checked="checked"' : '';
        tmp += '<th><label><input type="checkbox" name="verCine"' + check + ' >Cine</label></th>';
        check = getPreference("verGeneral", true) ? 'checked="checked"' : '';
        tmp += '<th><label><input type="checkbox" name="verGeneral"' + check + ' >General</label></th>';
        check = getPreference("verDescargas", true) ? 'checked="checked"' : '';
        tmp += '<th><label><input type="checkbox" name="verDescargas"' + check + ' >Descargas</label></th>';
        check = getPreference("verSubtitulos", true) ? 'checked="checked"' : '';
        tmp += '<th><label><input type="checkbox" name="verSubtitulos"' + check + ' >Subtitulos</label></th>';
        tmp += '</thead><tbody><tr valign="top">';

        for (var t in types = [_TFILM, _TGEN, _TDOWN, _TSUB]) {
            tmp += '<td class="sites">';
            for (var i in linkSites) {
                if (linkSites[i].type == types[t]) {
                    var name = linkSites[i].name;
                    var title = name;
                    if (linkSites[i].regreq)
                        title += ' (requiere registro)';
                    var icon = '<img src="' + linkSites[i].icon + '" alt="icono de ' + name + '" title="' + title + '"/>';
                    check = getPreference(name, true) || typeof getPreference(name) == 'undefined' ? 'checked="checked"' : '';
                    tmp += '<label title="' + title + '"><input type="checkbox" name="' + name + '" ' + check + '></input>' + icon + ' ' + name;
                    if (linkSites[i].regreq)
                        tmp += ' <span class="regreq">(*)</span>';
                    tmp += '</label><br/>';
                }
            }
            tmp += '</td>';
        }
        tmp += '</tr>';
        var checked = getPreference('newwindow', true) ? 'checked="checked"' : '';
        tmp += '<tr><td colspan=4><label><input type="checkbox" ' + checked + ' name="newwindow">Abrir los enlaces en una nueva ventana</label></td></tr>';
        tmp += '<tr><td colspan=4><hr>Los sitios marcados con <span class="regreq">(*)</span> requieren registro.</td></tr>';

        // Nuevas preferencias
        for (pref in preferencesOptions) {
            var def = preferencesOptions[pref].def;
            name = preferencesOptions[pref].name;
            checked = getPreference(name, def) ? 'checked="checked"' : '';
            var text = preferencesOptions[pref].text;
            tmp += '<tr><td colspan=4><label><input type="checkbox" ' + checked + ' name="' + name + '">' + text + '</label></td></tr>';
        }

        // Limite en recomendaciones y TOPs
        var limite = getPreference('limit',20);
        tmp +='<tr><td colspan=4><label>Nº de películas a mostrar en Recomendaciones y TOP: <input type="text" value="'+limite+'" name="limit"></label></td></tr>';

        tmp += '</tbody></table>';

        tmp += '<br/><fieldset><legend>Estilo de las puntuaciones</legend><div style="text-align: left"><label><input type="radio" name="ratingStyle" value="default" >Estilo por defecto</input></label><br/>';
        for (t in ratingStyles) {
            tmp += '<label><input type="radio" name="ratingStyle" value="' + ratingStyles[t].code + '">' + ratingStyles[t].name + ': <img src="' + ratingStyles[t].iconOn + '"><img src="' + ratingStyles[t].iconOn + '"><img src="' + ratingStyles[t].iconOn + '"><img src="' + ratingStyles[t].iconHalf + '"><img src="' + ratingStyles[t].iconOff + '"><img src="' + ratingStyles[t].iconOff + '"></input></label><br/>';
        }
        tmp += '</div></fieldset>';

        tmp += '<button id="saveButton" title="Guarda las preferencias y cierra el panel de configuración">Guardar preferencias</button>';

        prefs.innerHTML += tmp;
        d.body.appendChild(prefs);
        d.getElementById("saveButton").addEventListener("click", savePreferences, true);
        d.getElementById("closeButton").addEventListener("click", hidePreferences, true);
        d.getElementById("backgroundLayer").addEventListener("click", hidePreferences, true);
        loadPreferences();
        
        log("-mostradas preferencias");
    }

    // Por ahora solo los radio, preparar para todos
    function loadPreferences() {
      xpath = 'id("fap_prefs")//input[@type="radio"]';
      iterator = document.evaluate(xpath, d, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE , null);
      while (nodo = iterator.iterateNext()) {
        valor = getPreference(nodo.name);
        if (typeof valor == "undefined") {
          nodo.checked = nodo.value == "default";
        } else {
          nodo.checked = (nodo.value == valor);
        }
      }	
    }

    function savePreferences() {
      var xpath = 'id("fap_prefs")//input';
      var iterator = document.evaluate(xpath, d, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE , null);
      var nodo = null;
      while (nodo = iterator.iterateNext()) {
        switch (nodo.type) {
          case "checkbox":setPreference(nodo.name,nodo.checked);break;
          case "text":setPreference(nodo.name,nodo.value);break;
          case "radio":if (nodo.checked) {setPreference(nodo.name,nodo.value)};break;
        }
      }	
      alert('Los cambios tendrán efecto al recargar la página.');
      hidePreferences();        
    }

    function hidePreferences() {
        d.body.removeChild(d.getElementById('fap_prefs'));
        d.body.removeChild(d.getElementById('backgroundLayer'));
    }

    // ************************ FIN PREFERENCIAS *********************************************

    function getLinkSitesCode(type, title, titletr) {
        html = '';
        for (var i in linkSites) {
            // @todo: si la preferencia es false la consulta se hace dos veces, optimizar
            if (linkSites[i].type == type && ( getPreference(linkSites[i].name) || typeof getPreference(linkSites[i].name) == 'undefined' )) {
                var sicon = linkSites[i].icon;
                var stit = linkSites[i].name;
                var sstr = '';
                var target = getPreference('newwindow') ? '_blank' : '_self';
                if (linkSites[i].search.search(/%searchtr/) > -1)
                    sstr = linkSites[i].search.replace(/%searchtr/, linkSites[i].method(titletr));
                else
                    sstr = linkSites[i].search.replace(/%searchvo/, linkSites[i].method(title));
                html += '&nbsp;<a href="' + sstr + '" target="' + target + '"><img src="' + sicon + '" width=16 height=16 alt="' + stit + '" title="' + stit + '"></a>';
            }
        }
        return html;
    }

    function addLinkSites(elem, title, titletr) {
        log("Añadir enlaces a otros sitios web");
        for (var t in types = [_TFILM, _TGEN, _TDOWN, _TSUB]) {
            var txt = '';
            var tmp = '';
            var view = false;
            if (types[t] == _TFILM) {
                txt = 'Ficha en: ';
                view = getPreference("verCine", true);
            }
            else if (types[t] == _TGEN) {
                txt = 'Buscar en: ';
                view = getPreference("verGeneral", true);
            }
            else if (types[t] == _TDOWN) {
                    txt = 'Descargar de: ';
                    view = getPreference("verDescargas", true);
                }
                else if (types[t] == _TSUB) {
                        txt = 'Subtítulos en: ';
                        view = getPreference("verSubtitulos", true);
                    }
                    else
                        alert("Error en addLinkSites(). Informe al autor.");
            if (view) {
                for (var i in linkSites) {
                    // @todo: si la preferencia es false la consulta se hace dos veces, optimizar
                    if (linkSites[i].type == types[t] && ( getPreference(linkSites[i].name) || typeof getPreference(linkSites[i].name) == 'undefined' )) {
                        var sicon = linkSites[i].icon;
                        var stit = linkSites[i].name;
                        var sstr = '';
                        var target = getPreference('newwindow', true) ? '_blank' : '_self';
                        if (linkSites[i].search.search(/%searchtr/) > -1)
                            sstr = linkSites[i].search.replace(/%searchtr/, linkSites[i].method(titletr));
                        else
                            sstr = linkSites[i].search.replace(/%searchvo/, linkSites[i].method(title));

                        tmp += '&nbsp;<a href="' + sstr + '" target="' + target + '"><img src="' + sicon + '" width=16 height=16 alt="' + stit + '" title="' + stit + '"></a>';
                    }
                }
            }

            if (tmp != '')
                elem.innerHTML += '<span style="padding-left: 1em; font-style: italic;">' + txt + tmp + '</span>';
        }
        log("-añadidos enlaces");
    }

    // Comprueba los cambios en las puntuaciones de los amigos
    function doRatingChange(table) {
        log("RatingChange");
        for (var i = 1; i < table.rows.length - 1; ++i) {
            var userid = table.rows[i].cells[0].firstChild.href.split('=')[1];
            var ratedfilms = table.rows[i].cells[3].textContent.split('.').join('');
            var oldratedfilms = GM_getValue(userid);
            if (typeof oldratedfilms != 'undefined') {
                var dif = ratedfilms - oldratedfilms;
                if (dif != 0) {
                    var prefix = dif > 0 ? '+' : '';
                    table.rows[i].bgColor = dif > 0 ? 'lightgreen' : '#FF6666';
                    table.rows[i].cells[3].textContent += ' (' + prefix + dif + ')';
                }
                ;
            }
            GM_setValue(userid, ratedfilms);
        }
        log("-fin RatingChange");
    }

    // CAMBIOS EN ALMAS GEMELAS
    // @todo: cambiar los nombres de las variables a algo medianamente coherente

    function getSavedSoulMates(n) {
        var sm = [];
        for (i = 1; i < n; i++) {
            var saved = GM_getValue("sm." + i);
            if (saved != undefined) {
                sm[i] = eval(saved);
            }
        }
        return sm;
    }

    function saveSoulMates(soulMates) {
        for (ix in soulMates) {
            GM_setValue("sm." + ix, soulMates[ix].toSource());
        }
        GM_setValue("sml",soulMates.toSource());
    }

    
    function readSoulMates(table) {
        var soulMates = [];
        for (i = 1; i < table.rows.length; i++) {
            var row = table.rows[i];
            id = row.cells[1].innerHTML.split("=")[2].split('"')[0];
            name = row.cells[1].firstChild.firstChild.textContent;
            affinity = row.cells[2].firstChild.firstChild.innerHTML.replace(',', '.');
            votes = row.cells[3].firstChild.innerHTML;
            soulMates[i] = {'id':id,'name':name,'affinity':affinity,'votes':votes};
        }
        return soulMates;
    }

    function findChangesAllSoulMates(soulMates, previous, nRows) {
        var changesAll = new Object;
        var siguen = "";
        changesAll.changed = false;
        var rows = [];
        for (j = 1; j < nRows; j++) {
            var changes = new Object;
            var sm = soulMates[j];
            var found = false;
            var i = 1;
            while ((i < nRows) && !found) {
                if (previous[i]['id'] == sm['id']) {
                    found = true;
                    changes.pos = i - j;
                    changes.affinity = sm['affinity'] - previous[i]['affinity'];
                    changes.votes = sm['votes'] - previous[i]['votes'];
                    changes.changed = (changes['pos'] != 0) || (changes['affinity'] != 0) || (changes['votes'] != 0);
                }
                i++;
            }
            changes.found = found;
            if (found) {siguen += ","+sm['name'];}
            rows[j] = changes;
            changesAll.changed = changesAll.changed || changes.changed || !found;
        }
        // Buscamos los caidos de la lista
        var caidos = [];
        for (j=1; j< nRows;j++) {
          var user = previous[j].name;
          if (siguen.indexOf(user) < 0) {
            caidos.push(user);
          }
        }
        changesAll.rows = rows;
        changesAll.fallen = caidos;
        changesAll.date = formatDate(new Date());
        return changesAll;
    }

    function prepareSoulMatesTable(table) {
        table.rows[0].cells[0].colSpan = 2;
        table.rows[0].cells[2].colSpan = 2;
        table.rows[0].cells[3].colSpan = 2;
        for (var i = 1; i < table.rows.length; i++) {
            var row = table.rows[i];
            var newCell = d.createElement('TD');
            //newCell.width = 25;
            newCell.innerHTML = "&nbsp;";
            row.insertBefore(newCell, row.cells[0].nextSibling);
            newCell = d.createElement('TD');
            newCell.width = 20;
            newCell.innerHTML = "&nbsp;";
            row.insertBefore(newCell, row.cells[3].nextSibling);
            newCell = d.createElement('TD');
            newCell.width = 20;
            newCell.innerHTML = "&nbsp;";
            row.insertBefore(newCell, row.cells[5].nextSibling);
        }
    }

    function applySoulMatesChanges(table, i, changes) {
        // ¿Cambio de posicion?
        if (changes.pos > 0) {
            table.rows[i].cells[1].innerHTML = '<img src="' + upimg + '"><span style="font-size:80%;color:#1FA012;">' + changes.pos + '</span>';
        } else if (changes.pos < 0) {
            table.rows[i].cells[1].innerHTML = '<img src="' + downimg + '"><span style="font-size:80%;color:#A0121F;">' + changes.pos + '</span>';
        }
        // ¿cambio de afinidad?
        if (changes.affinity > 0) {
            table.rows[i].cells[4].innerHTML = '<span style="font-size:85%;color:#1FA012;">(+' + changes.affinity.toFixed(2) + ')</span>';
        } else if (changes.affinity < 0) {
            table.rows[i].cells[4].innerHTML = '<span style="font-size:85%;color:#A0121F;">(' + changes.affinity.toFixed(2) + ')</span>';
        }
        // ¿cambio de valoradas?
        if (changes.votes > 0) {
            table.rows[i].cells[6].innerHTML = '<span style="font-size:85%;color:#1FA012;">(+' + changes.votes + ')</span>';
        } else if (changes.votes < 0) {
            table.rows[i].cells[6].innerHTML = '<span style="font-size:85%;color:#A0121F;">(' + changes.votes + ')</span>';
        }
    }

    function applyNewSoulMate(table, i) {
        table.rows[i].cells[1].innerHTML = '<img src="' + newimg + '">';
    }

    // Añade la leyenda de los caidos
    function applyFallenSoulMates(table,fallen){
      if (fallen.length > 0) {
        var tr = d.createElement('TR');
        var td = d.createElement('TD');
        td.innerHTML = 'Almas gemelas caidas de la lista: <b>'+fallen.join(', ')+'</b>';
        td.colSpan = 7;
        tr.appendChild(td);
        table.rows[1].parentNode.appendChild(tr);
       }    
    }

    function appliLastChangesTime(table,date) {
      if (typeof date != "undefined") {
        var tr = d.createElement('TR');
        var td = d.createElement('TD');
        td.innerHTML = 'Ultimos cambios detectados el '+date;
        td.colSpan = 7;
        tr.appendChild(td);
        table.rows[1].parentNode.appendChild(tr);
       }        
    }

    // Comprueba los cambios en las almas gemelas
    function doSoulMatesChanges() {
        // Localizamos la tabla con los datos de las 20 almas gemelas
        xpath = '//table[@class="list2"]';
        var table = document.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        var nRows = table.rows.length;
        // Leer los datos guardados en la configuración
        var previousSoulMates = getSavedSoulMates(nRows);
        // Leer las almas gemelas del html
        var currentSoulMates = readSoulMates(table, nRows);
        // Si no hay lectura anterior, nos saltamos todo
        if (previousSoulMates.length > 0) {
            // Prepara la tabla para las modificaciones
            prepareSoulMatesTable(table);
            // Obtengo los cambios
            var changesSoulMates = findChangesAllSoulMates(currentSoulMates, previousSoulMates, i, nRows);
            newChanges = changesSoulMates.changed;
            // leemos los cambios anteriores ultimos y procesamos (si los hay)
            var savedChangesSoulMates = eval(GM_getValue('soulMatesChanges'));
            
            if (!changesSoulMates.changed && (savedChangesSoulMates != undefined)) {
                log("No hay cambios en las almas gemelas, leemos los cambios anteriores");
                if (getPreference("KEEPSMCHANGES", true)) {
                    changesSoulMates = savedChangesSoulMates;
                }
            } else {
                log("Guardando los nuevos cambios");
                GM_setValue('soulMatesChanges', changesSoulMates.toSource());
            }
            // comparar y modificar
            for (i = 1; i < nRows; i++) {
                var changes = changesSoulMates.rows[i];
                if (changes.found) {
                    // ya la teniamos
                    if (changes.changed) {
                        applySoulMatesChanges(table, i, changes);
                    }
                } else {
                    // Es un alma gemela nueva
                    applyNewSoulMate(table, i);
                }
            }
            if (getPreference("SHOWSMFALLEN",true)) {
              applyFallenSoulMates(table,changesSoulMates.fallen);
            }
            if (newChanges || getPreference("KEEPSMCHANGES")) {
              appliLastChangesTime(table,changesSoulMates.date);
            }
        } else {
            log("No hay datos previos de almas gemelas");
        }
        // Guardar los nuevos datos
        saveSoulMates(currentSoulMates);
    }


    function doFlag2Title() {
        log("Poner nombre del país en las banderas");
        var imgs = d.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; ++i)
            if (isFlagImg(imgs[i]) && imgs[i].hasAttribute('alt'))
                imgs[i].setAttribute('title', imgs[i].getAttribute('alt'));
        log("-fin nombre a banderas");
    }

    function doAlt2Title() {
        log("alt2title");
        var imgs = d.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; ++i)
            if (imgs[i].hasAttribute('alt') && !imgs[i].hasAttribute('title'))
                imgs[i].setAttribute('title', imgs[i].getAttribute('alt'));
        log("-fin alt2title");
    }

    function doInterFilm_old(table) {
        log("InterFilm");

        var originalTitle = '';
        var translatedTitle = '';
        if (isAdmin) {
            originalTitle = table.rows[0].cells[0].childNodes[6].rows[0].cells[0].childNodes[1].rows[0].cells[1].textContent;
            translatedTitle = table.getElementsByTagName("SPAN")[0].textContent;
        }
        else {
            originalTitle = table.rows[0].cells[0].childNodes[5].rows[0].cells[0].childNodes[1].rows[0].cells[1].textContent;
            translatedTitle = table.getElementsByTagName("SPAN")[0].textContent;
        }

        if (originalTitle.indexOf('(') != -1)
            originalTitle = originalTitle.substr(0, originalTitle.indexOf('('));

        if (translatedTitle.indexOf('(') != -1)
            translatedTitle = translatedTitle.substr(0, translatedTitle.indexOf('('));

        originalTitle = originalTitle.trim();
        translatedTitle = translatedTitle.trim();

        log("-TÃ­tulo original: " + originalTitle + " - TÃ­tulo traducido: " + translatedTitle);

        var titlediv = isAdmin ? table.getElementsByTagName('div')[2] : table.getElementsByTagName('div')[1];

        addLinkSites(titlediv, originalTitle, translatedTitle);
        log("-fin InterFilm");
    }


    function doInterFilm() {
        log("InterFilm");
        var xpath = '/html/body/table[2]/tbody/tr/td[2]/table';
        var table = document.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

        var originalTitle = '';
        var translatedTitle = '';
        if (isAdmin) {
            originalTitle = table.rows[0].cells[0].childNodes[6].rows[0].cells[0].childNodes[1].rows[0].cells[1].textContent;
            translatedTitle = table.getElementsByTagName("SPAN")[0].textContent;
        }
        else {
            originalTitle = table.rows[0].cells[0].childNodes[5].rows[0].cells[0].childNodes[1].rows[0].cells[1].textContent;
            translatedTitle = table.getElementsByTagName("SPAN")[0].textContent;
        }

        if (originalTitle.indexOf('(') != -1)
            originalTitle = originalTitle.substr(0, originalTitle.indexOf('('));

        if (translatedTitle.indexOf('(') != -1)
            translatedTitle = translatedTitle.substr(0, translatedTitle.indexOf('('));

        originalTitle = originalTitle.trim();
        translatedTitle = translatedTitle.trim();

        log("-Título original: " + originalTitle + " - Título traducido: " + translatedTitle);

        // recogemos el tr padre de la columna 'productora'
        xpath = "//b[text()='PRODUCTORA']/parent::*/parent::*";
        var nodoProductora = document.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

        // Fichas
        addDataRow(nodoProductora, "verSubtitulos", 'SUBTITULOS', _TSUB, originalTitle, translatedTitle);
        addDataRow(nodoProductora, "verDescargas",'DESCARGAS', _TDOWN, originalTitle, translatedTitle);     
        addDataRow(nodoProductora, "verGeneral",'BUSCAR', _TGEN, originalTitle, translatedTitle);
        addDataRow(nodoProductora, "verCine",'FICHA', _TFILM, originalTitle, translatedTitle);

        log("-fin InterFilm");
    }

    function addDataRow(sibling, preference, title, type, originalTitle, translatedTitle) {
        if (getPreference(preference,true)) {
          var html = getLinkSitesCode(type, originalTitle, translatedTitle);
          if (html != "") {
            var nodoTr = d.createElement('tr');
            var nodoTd = d.createElement('td');
            nodoTd.align = "right";
            nodoTd.valign = "baseline";
            nodoTd.innerHTML = '<b>' + title + '</b>';
            nodoTr.appendChild(nodoTd);
            nodoTd = d.createElement('td');
            nodoTd.innerHTML = html
            nodoTr.appendChild(nodoTd);
            sibling.parentNode.insertBefore(nodoTr, sibling.nextSibling);
          }
        }
    }


    function installSearchEngine() {
        log("Instalando buscador");
        window.setTimeout("window.sidebar.addSearchEngine('http://mycroft.mozdev.org/install.php/1913/filmaffinity_es.src', 'http://mycroft.mozdev.org/install.php/1913/filmaffinity_es.gif', 'FilmAffinity ES', 'as');", 50);
        log("-instalado");
    }


    function doAddExtraStats(totalCountries) {
        var tables = d.getElementsByTagName('TABLE');
        var table = null;
        for (var i = tables.length - 1; i > 0; --i) {
            if (tables[i].textContent.search("Nº de críticas validadas:") > -1) {
                table = tables[i];
                break;
            }
        }

        var clon = table.rows[table.rows.length - 2].cloneNode(true);
        clon.cells[0].textContent = "Nº de países diferentes:";
        clon.cells[1].innerHTML = "<b>" + totalCountries + "</b>";
        table.rows[table.rows.length - 2].parentNode.insertBefore(clon, table.rows[table.rows.length - 1]);
    }

    var limitUrls = ['/es/topgen.php','/es/smsrec.php'];
    /*
     * Modifica los menús originales de FA
    */
    function doAlterLimits() {
      var xpath = "";
      var nodo = null;
      var limit = getPreference("limit",20);
      for (ix in limitUrls) {
        xpath = '//a[@href="'+limitUrls[ix]+'"]';
        nodo = document.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        if (typeof nodo != "undefined") {
          nodo.href = nodo.href + "?limit="+limit;
        }
      }
    }

    function doAddMenus() {
        // Dirección base de los menus
        var baseXPath = '/html/body/table[2]/tbody/tr/td/table/tbody';
        var iPath = '/tr/td/table/tbody/tr/td/i[text()="';
        var parentPath = '"]/parent::*/parent::*/parent::*/parent::*/parent::*/parent::*';
        var container = document.evaluate(baseXPath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

        for (ix in menus)
        {
            menu = menus[ix];
            if (getPreference(menu.cond, true)) {
                xpath = baseXPath + iPath + menu['anchor'] + parentPath;
                var nodoAnterior = document.evaluate(xpath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                var html = '<td><table width="150" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff" class="menu"><tbody><tr><td class="menutitle"><i>';
                html = html + menu['name'] + '</i></td></tr>';
                for (ox in menu['options'])
                {
                    var option = menu['options'][ox];
                    var id = "IX" + ix + "OX" + ox;
                    html += '<tr><td class="menu"><a id="' + id + '" href="' + option['href'] + '" target="' + option['target'] + '"'
                    html += '>' + option['title'] + '</a></td></tr>';
                }
                html += '</tbody></table></td>';
                var fapp = d.createElement('tr');
                fapp.innerHTML = html;
                if (nodoAnterior != null) {
                    if (menu['position'] == ANCHOR_AFTER) {
                        container.insertBefore(fapp, nodoAnterior.nextSibling);
                    }
                    else {
                        container.insertBefore(fapp, nodoAnterior);
                    }
                    for (var ox in menu['options'])
                    {
                        option = menu['options'][ox];
                        id = "IX" + ix + "OX" + ox;
                        if (option['onclick'] != null) {
                            d.getElementById(id).addEventListener("click", option['onclick'], true);
                        }
                    }
                }
            }
        }
    }

    function doCaptureLists() {
        log('Captura Listas');
        var xPath = '/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/table/tbody/tr/td/span[text()="Nombre"]';
        var nodoSpan = document.evaluate(xPath, d, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        var table = nodoSpan.parentNode.parentNode.parentNode;
        var listas = [];
        deleteValues("list.");
        for (var i = 1; i < table.rows.length; i++) {
            var listName = table.rows[i].cells[0].firstChild.firstChild.data;
            if (listName.indexOf('(') != -1)
                listName = listName.substr(0, listName.indexOf('(')).trim();

            var listId = table.rows[i].cells[0].firstChild.href.split('=')[1];
            listas[i] = {'id':listId,'name':listName};
            log('lista: (' + listId + ') ' + listName);
            GM_setValue("list." + listId, listName);
        }

        log('Fin captura listas');
    }

    function doChangeRatingStyle() {
        log("Cambiar estilo de las puntuaciones");
        // esto da problemas si la película sólo está votada por 1 alma gemela, se parte la imagen
        // http://www.filmaffinity.com/es/film589794.html
        // http://www.filmaffinity.com/es/film743764.html
        //
        GM_addStyle('td[width="140"] { width: 160px; }');
        GM_addStyle('.ratingimg { width: 16px; height: 16px; border: 0; margin: 0; padding: 0; }');

        var schema = getPreference('ratingStyle');
        log("--Cambiar estilo a: " + schema);
        if (schema == 'default' || typeof schema == 'undefined') {
            log("--Sin cambios");
            return;
        }

        var imgs = document.getElementsByTagName('IMG');
        for (i = 0; i < imgs.length; ++i) {
            if (isRatingImg(imgs[i]) && !imgs[i].hasAttribute('id')) { //solución temporal
                var rating = getRatingFromImg(imgs[i]);
                var j = 0;
                while (j < rating) {
                    changeImageRatingStyle(imgs[i], ratingStyles[schema].iconOn, rating);
                    ++j;
                }

                while (j < 10) {
                    changeImageRatingStyle(imgs[i], ratingStyles[schema].iconOff, rating);
                    ++j;
                }

                if (imgs[i].hasAttribute('id')) {
                    //	imgs[i].setAttribute('style', 'display: none;');
                    //	imgs[i].addEventListener('change', chang, true);
                }
                else
                    imgs[i].parentNode.removeChild(imgs[i]);
            }
        }
        log("-fin cambiar estilo");
    }


    function doAddContriesFlags() {
        log("Añadir banderitas");
        var tables = d.getElementsByTagName('TABLE');
        var table = null;
        for (var i = tables.length - 1; i > 0; --i) {
            if (tables[i].textContent.search('Mis votos por país') > -1) {
                table = tables[i];
                break;
            }
        }

        for (i = 1; i < table.rows.length; ++i) {
            table.rows[i].cells[0].setAttribute('style',
                    'padding-left: 19px; background: white url("http://www.filmaffinity.com/imgs/countries/' + getCountryCode(table.rows[i].cells[0].textContent) + '.jpg") no-repeat scroll center left');
        }
        var countries = table.rows.length - 1;
        log("-fin añadir banderitas. total=" + countries);
        return countries;
    }


    function doAddFlagsToOptionsSel() {
        if (inTopGen())
            doAddFlagsToOptions(d.forms[1].elements[2]);
        else if (inAdvSearch())
            doAddFlagsToOptions(d.forms[1].elements[9]);
    }

    function hideQuickListPanel() {
        d.body.removeChild(d.getElementById('panel_listas'));
        d.body.removeChild(d.getElementById('backgroundLayer'));
    }



    function doAddFilmToList(film, list) {
        var url = "http://www.filmaffinity.com/es/edtmovielists.php?movie_id=";
        url += film + "&rp=%2Fes%2Ftour.php%3Fidtour%3D29";
        var panel = d.getElementById('panel_listas');
        panel.style.textAlign = "center";
        panel.style.verticalAlign = "middle";
        panel.style.display = "table-cell";
        altura = ((panel.clientHeight) / 2) - 16;
        ancho = ((panel.clientWidth) / 2) - 16;
        panel.innerHTML = '<span></span><img style="display:block;margin-left:' + ancho + 'px;margin-top:' + altura + 'px;" src="' + waitimg + '">';
        d.getElementById("backgroundLayer").removeEventListener("click", hideQuickListPanel, true);
        estado = document.body.style.cursor;
        document.body.style.cursor = 'wait';
        post(url, "atl[]=" + list, function() {
            hideQuickListPanel();
            windows.status = "Añadida pelicula a lista";
        });
        document.body.style.cursor = estado;
    }

    function openQuickListPanel() {
        var ancho = 320;
        var lpc = Math.floor((document.body.clientHeight*0.75) / 14);
        pelicula = this.id;
        //Obtenemos las listas desde la configuración
        listas = getValues("list.");
        listas.sort(function(a,b){return a - b;});
        // Por si queremos simular mas listas
        //for (n=1;n<10;n++) {
        //  listas.push(listas[0]);
        //}
        var n = listas.length;
        var nColumnas = Math.ceil(n / lpc);
        var alto = (Math.min(n,lpc)+1) * 15;
        //alert('Elementos: '+n+' Columnas: '+nColumnas+' lpc: '+lpc+' alto:'+alto);
        //alert(alto);
        GM_addStyle('#backgroundLayer { width: 100%; height: 100%; background-color: black; position: fixed; left: 0; right: 0; top: 0; bottom: 0; opacity: .7; }');
        GM_addStyle('#panel_listas { color: black; background-color: #003366; text-align: center; border: 0px solid gray; width: ' + (ancho*nColumnas+2) + 'px; height: ' + alto + 'px; opacity: 1; margin: auto; position: fixed; left: 0; right: 0; top: 0; bottom: 0; overflow: auto; }');
        GM_addStyle('td.menu span.listItem {cursor:pointer;padding: 1px; color: #eeeeee; background-color: #415570; font-size: 9px; font-family: Verdana,Arial,Helvetica,sans-serif; text-decoration: none; text-indent: 3px; cursor: hand; display: block}');
        GM_addStyle('td.menu span.listItem:hover {padding: 1px; color: #003366; background-color: #FFCC00; font-size: 9px; font-family: Verdana,Arial,Helvetica,sans-serif; text-decoration: none; text-indent: 3px;  cursor: hand; display: block }');
        var background = d.createElement('DIV');
        background.id = 'backgroundLayer';
        d.body.appendChild(background);

        var panel = d.createElement('DIV');
        panel.id = 'panel_listas';

        var html = '<table width="'+ancho*nColumnas+'px" cellspacing="0" cellpadding="0" border="0" bgcolor="#415570" class="rmenu">';
        html +='<tbody><tr><td colspan="'+nColumnas+'" class="menutitle"><i>';
        html += 'Seleccione lista</i></td></tr>';
        var ipc = lpc;
        for (var row = 0; row < ipc; row++)
        {
            html += '<tr>';
            for (var col = 0; col < nColumnas;col++)
            {
                var i = (ipc * col) + row;
                if (i<n) {
                    id = listas[i];
                    name = GM_getValue('list.' + listas[i]);
                    html += '<td class="menu"><span class="listItem" id="' + id + '" href="#">' + name + '</span></td>';
                }
            }
            html += '</tr>';
        }

        html += '</tbody></table>';
        panel.innerHTML = html;
        d.body.appendChild(panel);

        d.getElementById("backgroundLayer").addEventListener("click", hideQuickListPanel, true);
        for (i = 0; i < listas.length; i++)
        {
            id = listas[i];
            d.getElementById(id).addEventListener("click", function() {
                doAddFilmToList(pelicula, this.id);
            }, false);
        }

        return false;
    }


    function doAddQuickList() {
        // Path para localizar todos los 'añadir a Lista';
        // xpath = "/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/div/table/tbody/tr/td[2]/table/tbody/tr/td/a";
        GM_addStyle('.addToList {margin-left:4px;cursor:pointer;width:9px;height:9px;}');
        var anchors = getElementsByClassName(d, 'a', 'addl');
        for (var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.textContent == "Añadir a listas") {
                var button = d.createElement('IMG');
                button.className = 'addToList';
                button.src = addListimg;
                button.alt = "Añadir pelicula a listas";
                button.id = anchor.href.split('=')[1].split('&')[0];
                button.addEventListener("click", openQuickListPanel, false);
                anchor.parentNode.appendChild(button);
            }
        }
    }


    function doAddFlagsToOptions(o) {
        log("Añadir banderas a options");
        for (var i = 0; i < o.options.length; ++i) {
            o.options[i].setAttribute('style', 'padding-left: 19px; background: white url("http://www.filmaffinity.com/imgs/countries/' + o.options[i].value + '.jpg") no-repeat scroll center left');
        }

        o.setAttribute('style', 'padding-left: 19px; background: white url("http://www.filmaffinity.com/imgs/countries/' + o.options[o.selectedIndex].value + '.jpg") no-repeat scroll center left');

        o.addEventListener("change", doAddFlagsToOptionsSel, true);
        o.addEventListener("keyup", doAddFlagsToOptionsSel, true);

        log("-fin banderas a options");
    }


    function changeImageRatingStyle(img, icon, rating) {
        var tmpimg = d.createElement('IMG');
        tmpimg.className = 'ratingimg';
        tmpimg.src = icon;
        tmpimg.alt = tmpimg.title = rating + ' - ' + ratings[rating];
        img.parentNode.appendChild(tmpimg);
    }

    function processSearch() {
        var divs = d.getElementsByTagName('DIV');
        var par;
        for (var i = 0; i < divs.length; ++i) {
            if (divs[i].textContent.indexOf('Resultados por título') != -1) {
                par = divs[i].parentNode.parentNode.parentNode;
                addLinkSites(par, d.forms[0].elements[0].value, d.forms[0].elements[0].value);
            }
        }
        // formulario
        var stype = url.substr(url.lastIndexOf('=') + 1);
        var elem = d.forms[0].elements[1];
        for (i = 0; i < elem.options.length; ++i)
            if (elem.options[i].value == stype) {
                elem.selectedIndex = i;
                break;
            }
        d.forms[0].elements[0].focus();
    }


    function doFixEnglishLink() {
        for (var i = 0; i < d.links.length; ++i)
            if (d.links[i].href == 'http://www.filmaffinity.com/en/main.html')
                d.links[i].href = url.replace('/es/', '/en/');
    }

    //showPreferences(); return;

    //******************************************
    var GM_setValue_SAFE=(GM_setValue.toString().search(/cookie/i)==-1);
    if (!GM_setValue_SAFE) return;
    var date = new Date();
    log('Inicio (' + date + ')');
    log(navigator.userAgent);
    log(appName + ' ' + appVersion);

    GM_registerMenuCommand('Configurar ' + appName + ' ' + appVersion + '...', showPreferences);
    GM_registerMenuCommand('Ver información de depurado', showLog);

    log("¿Admin? " + isAdmin);

    if (url.search(/\/filter\.php/ig) > -1) {
        return;
    }


    if (inMyFriends()) {
        var tables = document.getElementsByTagName('table');
        for (var i = tables.length - 1; i > 0; --i) {
            if (tables[i].textContent.search('Nombre/Nick') > -1) {
                doRatingChange(tables[i]);
                break;
            }
        }
    }

    // Pagina de pelicula, añadir enlaces
    if (inFilm()) {
        doFunction = (getPreference("LINKSINPROFILE", true)) ? doInterFilm : doInterFilm_old;
        if (isAdmin)
            doFunction(d.getElementsByTagName('table')[17]);
        else
            doFunction(d.getElementsByTagName('table')[16]);
    }

    // Cambios en Almas Gemelas
    if (inSoulMates() && getPreference('SHOWSMCHANGES', true)) {
        doSoulMatesChanges();
    }


    // Pagina de Listas, capturar nombres
    if (inLists()) {
        doCaptureLists();
    }

    // Pagina de tours, añadimos quickList
    if ((inTour() || inSoulMatesRec() || inUserRec() || inMyVotes() || inAutotour())
            && (getPreference('SHOWQUICKLIST'))) {
        doAddQuickList();
    }

    if (!inMyData())
        doChangeRatingStyle();

    if (inStats())
        doExtraStats(d.getElementsByTagName('table')[16]);

    if (inSearch()) {
        processSearch();
        doChangeRatingStyle();
    }

    if (inMyData()) {
        doAddExtraStats(doAddContriesFlags());
    }

    if (inTopGen() || inAdvSearch()) {
        doAddFlagsToOptionsSel();
    }

    doAlt2Title();
    //doAddForumLink();
    doAddMenus();
    if (getPreference('CHANGELIMIT',false)) {    
      doAlterLimits();
    }
    doFixEnglishLink();
    //doRemoveAds();


    log("Fin (" + date + ")");

};


